package com.musicsonar.android.activity;

import java.util.List;
import java.util.Random;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.SessionStore;
import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
import com.musicsonar.android.bean.PlayList;
import com.musicsonar.android.dialog.MusicSonarDialog;
import com.musicsonar.android.menu.IconContextMenu;
import com.musicsonar.android.player.MusicSonarPlayer;
import com.musicsonar.android.utils.MusicSonarConstant;
import com.musicsonar.android.utils.MusicSonarUtils;
import com.musicsonar.android.utils.SongsManager;
import com.musicsonar.android.utils.WebImage;

public class MusicSonarActivity extends Activity implements OnCompletionListener, OnBufferingUpdateListener, SeekBar.OnSeekBarChangeListener {

	private ImageButton btnPlay;
	private ImageButton btnForward;
	private ImageButton btnBackward;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	//private ImageButton btnRepeat;
	private ImageButton btnShuffle;
	private ImageButton btnPlayList;
	private ImageButton btnShare;
	private ImageButton btnMenu;
	private ImageButton btnClose;
	private SeekBar songProgressBar;
	private TextView songTitleLabel;
	private TextView songCurrentDurationLabel;
	private TextView songTotalDurationLabel;
	private ImageView songImageTarget;
	// Media Player
	public static MusicSonarPlayer mp;
	// Handler to update UI timer, progress bar etc,.
	private Handler mHandler = new Handler();
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	private int currentSongIndex = -1;

	// Waiting window
	private static MusicSonarDialog dialog;

	public static MusicSonarActivity me;

	//private static Boolean isRepeat;

	private static Boolean isShuffle;

	// Preferences Access
	private SharedPreferences sharedPrefs;
	private String mQuality;

	private int errorCount = 0;

	private GoogleAnalyticsTracker tracker;

	private AdView adView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.player);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.header_player);

		// All player buttons
		btnPlay = (ImageButton) findViewById(R.id.btnPlay);
		btnForward = (ImageButton) findViewById(R.id.btnForward);
		btnBackward = (ImageButton) findViewById(R.id.btnBackward);
		btnNext = (ImageButton) findViewById(R.id.btnNext);
		btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
		//btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
		btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
		btnPlayList = (ImageButton) findViewById(R.id.btnPlayList);
		btnShare = (ImageButton) findViewById(R.id.btnShare);
		btnMenu = (ImageButton) findViewById(R.id.btnMenu);
		btnClose = (ImageButton) findViewById(R.id.btnClose);
		songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
		songTitleLabel = (TextView) findViewById(R.id.songTitleText);
		songImageTarget = (ImageView) findViewById(R.id.songImageTarget);
		songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
		songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

		// Mediaplayer
		mp = new MusicSonarPlayer();
		me = this;
		sharedPrefs = PreferenceManager.getDefaultSharedPreferences(me);
		mQuality = sharedPrefs.getString("sound_quality", "low");

		// Listeners
		songProgressBar.setOnSeekBarChangeListener(this); // Important
		mp.setOnBufferingUpdateListener(this);
		mp.setOnCompletionListener(this); // Important

		//isRepeat = sharedPrefs.getBoolean("isRepeat", Boolean.FALSE);
		isShuffle = sharedPrefs.getBoolean("isShuffle", Boolean.FALSE);

/*
		if(isRepeat){
			btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
		}
*/
		if(isShuffle){
			btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
		}

		if(currentSongIndex == -1){
			currentSongIndex = sharedPrefs.getInt("currentSongIndex", -1);
		}

		btnClose.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				System.runFinalizersOnExit(true);
				System.exit(0);
				try{
					android.os.Process.killProcess(android.os.Process.myPid());
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});

		/**
		 * PlayList button click event
		 * show actual playlist 
		 * */
		btnPlayList.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				Intent i = new Intent(getApplicationContext(), TabPlayListActivity.class);
				startActivityForResult(i, 100);
			}
		});

		/**
		 * Share button click event
		 * share on facebook a song 
		 * */
		btnShare.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				if(SongsManager.actualSong == null){
					Toast.makeText(me, getText(R.string.facebook_shared_song_empty), Toast.LENGTH_LONG).show();
					return;
				}
				createShareContextMenu();
				tracker.trackEvent("Player",  // Category
						"Click",  // Action
						"Share",  // Label
						0); // Value
			}
		});

		/**
		 * Play button click event
		 * plays a song and changes button to pause image
		 * pauses a song and changes button to play image
		 * */
		btnPlay.setOnClickListener(new View.OnClickListener() {

			public void onClick(View view) {
				// check for already playing
				if(mp.isPlaying()){
					// Pause song
					mp.pause();
					// Changing button image to play button
					btnPlay.setImageResource(R.drawable.btn_play);
				}else{
					if(currentSongIndex == -1){
						if(SongsManager.getActualPlayList().getSongList().size() > 0){
							playSong(0, me);
							// Changing button image to pause button
							btnPlay.setImageResource(R.drawable.btn_pause);
						}else{
							Intent i = new Intent(getApplicationContext(), TabPlayListActivity.class);
							startActivityForResult(i, 100);
							btnPlay.setImageResource(R.drawable.btn_play);
						}
					}else{
						if(SongsManager.getActualPlayList().getSongList().size() > 0){
							if(mp.getTotalDuration() > 0){
								// Resume song
								mp.start();
							}else{
								if(SongsManager.getActualPlayList().getSongList().size() >= currentSongIndex){
									playSong(currentSongIndex, me);
								}else{
									clearPlayerScreen();
									Intent i = new Intent(getApplicationContext(), TabPlayListActivity.class);
									startActivityForResult(i, 100);
									return;
								}
							}
							// Changing button image to pause button
							btnPlay.setImageResource(R.drawable.btn_pause);
						}else{
							clearPlayerScreen();
							Intent i = new Intent(getApplicationContext(), TabPlayListActivity.class);
							startActivityForResult(i, 100);
							return;
						}
					}
				}

				tracker.trackEvent("Player",  // Category
									"Click",  // Action
									"Play",  // Label
									0); // Value
			}
		});

		/**
		 * Forward button click event
		 * Forwards song specified seconds
		 * */
		btnForward.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// get current song position				
				int currentPosition = mp.getCurrentPosition();
				// check if seekForward time is lesser than song duration
				if(currentPosition + seekForwardTime <= mp.getTotalDuration()){
					// forward song
					mp.seekTo(currentPosition + seekForwardTime);
				}else{
					// forward to end position
					mp.seekTo(mp.getTotalDuration());
				}

				tracker.trackEvent("Player",  // Category
						"Scroll",  // Action
						"Forward",  // Label
						0); // Value
			}
		});

		/**
		 * Backward button click event
		 * Backward song to specified seconds
		 * */
		btnBackward.setOnClickListener(new View.OnClickListener() {

			public void onClick(View arg0) {
				// get current song position				
				int currentPosition = mp.getCurrentPosition();
				// check if seekBackward time is greater than 0 sec
				if(currentPosition - seekBackwardTime >= 0){
					// forward song
					mp.seekTo(currentPosition - seekBackwardTime);
				}else{
					// backward to starting position
					mp.seekTo(0);
				}

				tracker.trackEvent("Player",  // Category
						"Scroll",  // Action
						"Backward",  // Label
						0); // Value
			}
		});
		
		/**
		 * Next button click event
		 * Plays next song by taking currentSongIndex + 1
		 * */
		btnNext.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View view) {
				if(mp.isPlaying()){
					mp.stop();
				}
				// Validate items in songsList available
				if(SongsManager.getActualPlayList().getSongList().size() > 0){
					// check for repeat is ON or OFF
					/*if(isRepeat){
						// repeat is on play same song again
						playSong(currentSongIndex, me);
					} else */if(isShuffle){
						// shuffle is on - play a random song
						Random rand = new Random();
						int thisSongIndex = rand.nextInt((SongsManager.getActualPlayList().getSongList().size() - 1) - 0 + 1) + 0;
						// check if next song is there or not
						if(thisSongIndex < (SongsManager.getActualPlayList().getSongList().size() - 1)){
							playSong(thisSongIndex + 1, me);
						}else{
							// play first song
							playSong(0, me);
						}
					} else{
						// check if next song is there or not
						if(currentSongIndex < (SongsManager.getActualPlayList().getSongList().size() - 1)){
							playSong(currentSongIndex + 1, me);
						}else{
							// play first song
							playSong(0, me);
						}
					}
				}else{
					currentSongIndex = -1;
					clearPlayerScreen();
				}

				tracker.trackEvent("Player",  // Category
						"Click",  // Action
						"Next Song",  // Label
						0); // Value
			}
		});
		
		/**
		 * Back button click event
		 * Plays previous song by currentSongIndex - 1
		 * */
		btnPrevious.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View view) {
				if(mp.isPlaying()){
					mp.stop();
				}
				// Validate items in songsList available
				if(SongsManager.getActualPlayList().getSongList().size() > 0){
					// check for repeat is ON or OFF
					/*if(isRepeat){
						// repeat is on play same song again
						playSong(currentSongIndex, me);
					} else */if(isShuffle){
						// shuffle is on - play a random song
						Random rand = new Random();
						int thisSongIndex = rand.nextInt((SongsManager.getActualPlayList().getSongList().size() - 1) - 0 + 1) + 0;
						if(thisSongIndex > 0){
				        	// play selected song
							playSong(thisSongIndex, me);
						}else{
				        	// play last song
							playSong(thisSongIndex, me);
						}
					} else {
						if(currentSongIndex > 0){
				        	// play selected song
							playSong(currentSongIndex - 1, me);
						}else{
				        	// play last song
							playSong(SongsManager.getActualPlayList().getSongList().size() - 1, me);
						}
					}
				}else{
					currentSongIndex = -1;
					clearPlayerScreen();
				}

				tracker.trackEvent("Player",  // Category
						"Click",  // Action
						"Previous Song",  // Label
						0); // Value
			}
		});
		
		/**
		 * Button Click event for Repeat button
		 * Enables repeat flag to true
		 * */
/*		btnRepeat.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				if(isRepeat){
					isRepeat = Boolean.FALSE;
					Toast.makeText(me, getText(R.string.repeat_off), Toast.LENGTH_SHORT).show();
					btnRepeat.setImageResource(R.drawable.btn_repeat);
				}else{
					// make repeat to true
					isRepeat = Boolean.TRUE;
					Toast.makeText(me, getText(R.string.repeat_on), Toast.LENGTH_SHORT).show();
					// make shuffle to false
					isShuffle = Boolean.FALSE;
					btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}
				SharedPreferences.Editor editor = sharedPrefs.edit();
				editor.putBoolean("isRepeat", isRepeat);
				editor.putBoolean("isShuffle", isShuffle);
				editor.commit();
			}
		});*/
		
		/**
		 * Button Click event for Shuffle button
		 * Enables shuffle flag to true
		 * */
		btnShuffle.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				if(isShuffle){
					isShuffle = Boolean.FALSE;
					Toast.makeText(me, getText(R.string.shuffle_off), Toast.LENGTH_SHORT).show();
					btnShuffle.setImageResource(R.drawable.btn_shuffle);
				}else{
					// make repeat to true
					isShuffle= Boolean.TRUE;
					Toast.makeText(me, getText(R.string.shuffle_on), Toast.LENGTH_SHORT).show();
					// make shuffle to false
					//isRepeat = Boolean.FALSE;
					btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
					//btnRepeat.setImageResource(R.drawable.btn_repeat);
				}
				SharedPreferences.Editor editor = sharedPrefs.edit();
				//editor.putBoolean("isRepeat", isRepeat);
				editor.putBoolean("isShuffle", isShuffle);
				editor.commit();
			}
		});

		/**
		 * Button Click event for Menu button
		 * Show Context Menu
		 * */
		btnMenu.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				createContextMenu();
			}
		});

		MusicSonarConstant.mFacebook = new Facebook(MusicSonarConstant.FACEBOOK_APPLICATION_ID);
		MusicSonarConstant.mFacebook.setAccessToken(sharedPrefs.getString("access_token", null));
		if(MusicSonarConstant.mFacebook.getAccessToken() != null){
			MusicSonarConstant.mFacebook.setAccessExpires(0);
		}
		MusicSonarConstant.isValidated = sharedPrefs.getBoolean("access_validated", Boolean.FALSE);
		MusicSonarConstant.accountName = sharedPrefs.getString("account_name", null);
		MusicSonarConstant.accountID = sharedPrefs.getLong("account_id", 0);

		if(!MusicSonarConstant.isValidated && MusicSonarUtils.isOnline(this)){
			(new Thread(new Runnable() {
				
				public void run() {
					Toast.makeText(me, getText(R.string.validation_account),Toast.LENGTH_LONG).show();
					// Obtain facebook objects to connection
					if(!SessionStore.restore(MusicSonarConstant.mFacebook, me)){
						MusicSonarConstant.mFacebook = new Facebook(MusicSonarConstant.FACEBOOK_APPLICATION_ID);
						if(!MusicSonarConstant.mFacebook.isSessionValid()) {
							String[] permissions = {"publish_stream", "publish_checkins", "offline_access", "read_stream", "user_events", "friends_events", "friends_status", "user_status", "friends_photos", "user_photos", "friends_about_me", "friends_website", "email", "friends_birthday", "friends_location", "photo_upload"};
							MusicSonarConstant.mFacebook.authorize(me, permissions, new Facebook.DialogListener() {
				                public void onComplete(Bundle values) {
				                	if(SessionStore.save(MusicSonarConstant.mFacebook, me)){
				                		MusicSonarUtils.getFacebookSessionInformation(me);
				    					Editor editor = sharedPrefs.edit();
				    					editor.putString("access_token", MusicSonarConstant.mFacebook.getAccessToken());
				    					editor.commit();
				                	}
				                }
					            public void onFacebookError(FacebookError error) {
					            	Toast.makeText(me, error.getMessage(), Toast.LENGTH_LONG).show();
					            }

					            public void onError(DialogError e) {
					            	
					            }

					            public void onCancel() {
					            	
					            }
							});
						}
					}else{
						MusicSonarUtils.getFacebookSessionInformation(me);
					}

					// Obtain account configurated on device
					if(MusicSonarConstant.accountID.longValue() == 0){
						Account[] accounts = AccountManager.get(me).getAccounts();
						for (Account account : accounts) {
							if(MusicSonarConstant.ACCOUNT_TYPE_GOOGLE.equals(account.type)){
								MusicSonarConstant.accountName = account.name;
		    					Editor editor = sharedPrefs.edit();
		    					editor.putString("account_name", MusicSonarConstant.accountName);
		    					editor.commit();
								break;
							}
						}
						if(MusicSonarConstant.accountName != null){
							MusicSonarConstant.accountID = MusicSonarUtils.getAccountID(MusicSonarConstant.accountName, MusicSonarConstant.facebookUID);
						}
						if(MusicSonarConstant.accountID.longValue() > 0){
	    					Editor editor = sharedPrefs.edit();
	    					editor.putLong("account_id", MusicSonarConstant.accountID);
	    					editor.commit();
							List<PlayList> recive = MusicSonarUtils.getSendedList(MusicSonarConstant.accountID);
							String message = "";
							if(recive != null && recive.size() > 0){
								for(PlayList pl : recive){
									message += "[" + pl.getName() + " - " + pl.getOwner() + "]\n";
								}
							}
							if(!"".equals(message)){
								Toast.makeText(me, message, Toast.LENGTH_LONG).show();
							}
						}
					}
					MusicSonarConstant.isValidated = Boolean.TRUE;
					Editor editor = sharedPrefs.edit();
					editor.putBoolean("access_validated", MusicSonarConstant.isValidated);
					editor.commit();

					Toast.makeText(me, getText(R.string.account_validates), Toast.LENGTH_LONG).show();
				}
			})).run();
		}
		// Google Ads
		adView = new AdView(me, AdSize.BANNER, "a14ff25bef8ad75");
		RelativeLayout layout = (RelativeLayout)findViewById(R.id.principal);
		layout.addView(adView);
		adView.loadAd(new AdRequest());

		// Google Analytics
		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.startNewSession("UA-34126154-1", 20, this);
	}

	private void createContextMenu(){
		Resources res = getResources();
		final IconContextMenu iconContextMenu = new IconContextMenu(me);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_playlist), R.drawable.ic_menu_playlist, 0);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_share_song), R.drawable.ic_menu_share, 1);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_preferences), R.drawable.ic_menu_preferences, 2);

		iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
			public void onClick(int menuId) {
				
				switch (menuId) {
					case 0:{ // playlist
							Intent i = new Intent(getApplicationContext(), TabPlayListActivity.class);
							startActivityForResult(i, 100);
							break;
							}
					case 1:{ // share song
							if(SongsManager.actualSong == null){
								Toast.makeText(me, getText(R.string.facebook_shared_song_empty), Toast.LENGTH_LONG).show();
								return;
							}
							createShareContextMenu();
						    break;
							}
					case 2:{ // preferences
							Intent i = new Intent(getApplicationContext(), PreferencesActivity.class);
							startActivity(i);
							break;
							}
				}
			}
		});
		iconContextMenu.createMenu(getText(R.string.music_sonar_options).toString()).show();
	}

	private void createShareContextMenu(){
		Resources res = getResources();
		final IconContextMenu iconContextMenu = new IconContextMenu(me);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_my_wall), R.drawable.ic_menu_my_wall, 0);
		iconContextMenu.addItem(res, getText(R.string.menu_btn_to_friends), R.drawable.ic_menu_to_friends, 1);

		iconContextMenu.setOnClickListener(new IconContextMenu.IconContextMenuOnClickListener() {
			public void onClick(int menuId) {
				
				switch (menuId) {
					case 0:{ // my wall
							publishSong();
							break;
							}
					case 1:{ // to friends
							shareSong();
						    break;
							}
				}
			}
		});
		iconContextMenu.createMenu(getText(R.string.music_sonar_options).toString()).show();
	}

	private void shareSong(){
		final Bundle params = new Bundle();
        params.putString("message", getText(R.string.facebook_shared_song_message).toString() + " [" + SongsManager.actualSong.getSongTitle() + "] " + getText(R.string.facebook_shared_song_message_end).toString());
        params.putString("link", MusicSonarConstant.FACEBOOK_FEED_URL + "&song_id="+SongsManager.actualSong.getSongID());
        params.putString("name", "MusicSonar - [" + SongsManager.actualSong.getSongTitle() + "]");
        params.putString("caption", "MusicSonar - " + getText(R.string.facebook_shared_caption));
        params.putString("description", SongsManager.actualSong.getSongTitle());
        params.putString("icon", MusicSonarConstant.FACEBOOK_FEED_IMAGE);
        params.putString("type", "link");
	    MusicSonarConstant.mFacebook.dialog(me, "apprequests", params, new Facebook.DialogListener() {
			
			public void onFacebookError(FacebookError e) {
			}
			
			public void onError(DialogError e) {
				Toast.makeText(me, e.getMessage(), Toast.LENGTH_LONG).show();
			}
			
			public void onComplete(Bundle values) {
				boolean publish = false;
				for(int i = 0; i < 100; i ++){
					String to = values.getString("to["+i+"]");
					if(to == null){
						break;
					}
					publish = true;
					
		            try {
		            	String songID = SongsManager.actualSong.getSongID();
		            	if(songID != null){
							MusicSonarConstant.mFacebook.request(to+"/feed", params, "POST");
		            	}else{
		            		Toast.makeText(me, getText(R.string.facebook_shared_problem), Toast.LENGTH_LONG).show();
		            	}
					} catch (Exception e) {
						Toast.makeText(me, e.getMessage(), Toast.LENGTH_LONG).show();
					}
				}
				if(publish){
					Toast.makeText(me, getText(R.string.facebook_shared_song_ok), Toast.LENGTH_LONG).show();
				}else{
					Toast.makeText(me, getText(R.string.facebook_shared_cancel), Toast.LENGTH_LONG).show();
				}
			}
			
			public void onCancel() {
				Toast.makeText(me, getText(R.string.facebook_shared_cancel), Toast.LENGTH_LONG).show();
			}
		});
	}

	private void publishSong(){
		final Bundle params = new Bundle();
		params.putString("message", getText(R.string.facebook_shared_song_message).toString() + " [" + SongsManager.actualSong.getSongTitle() + "] " + getText(R.string.facebook_shared_song_message_end).toString());
        params.putString("message", getText(R.string.facebook_shared_song_message).toString() + " [" + SongsManager.actualSong.getSongTitle() + "] " + getText(R.string.facebook_shared_song_message_end).toString());
        params.putString("link", MusicSonarConstant.FACEBOOK_FEED_URL + "&song_id="+SongsManager.actualSong.getSongID());
        params.putString("name", "MusicSonar - [" + SongsManager.actualSong.getSongTitle() + "]");
        params.putString("caption", "MusicSonar - " + getText(R.string.facebook_shared_caption));
        params.putString("description", SongsManager.actualSong.getSongTitle());
        params.putString("icon", MusicSonarConstant.FACEBOOK_FEED_IMAGE);
        params.putString("type", "link");
	    MusicSonarConstant.mFacebook.dialog(me, "feed", params, new Facebook.DialogListener() {
			
			public void onFacebookError(FacebookError e) {
			}
			
			public void onError(DialogError e) {
				Toast.makeText(me, e.getMessage(), Toast.LENGTH_LONG).show();
			}
			
			public void onComplete(Bundle values) {
				Toast.makeText(me, getText(R.string.facebook_shared_song_ok), Toast.LENGTH_LONG).show();
			}
			
			public void onCancel() {
				Toast.makeText(me, getText(R.string.facebook_shared_cancel), Toast.LENGTH_LONG).show();
			}
		});
	}

	/**
	 * Receiving song index from playlist view
	 * and play the song
	 * */
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 100){
        	currentSongIndex = data.getExtras().getInt("songIndex");
        	// play selected song
        	if(mp.isPlaying()){
        		mp.stop();
        	}
			playSong(currentSongIndex, me);
        }
        MusicSonarConstant.mFacebook.authorizeCallback(requestCode, resultCode, data);
    }

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		createContextMenu();
		return super.onPrepareOptionsMenu(menu);
	}

	public void playSong(int songIndex, MusicSonarDialog dialog){
		currentSongIndex = songIndex;
		SharedPreferences.Editor editor = sharedPrefs.edit();
		editor.putInt("currentSongIndex", currentSongIndex);
		editor.commit();
		// Play song
		try {
			MusicSonarConstant.currentPositionPaused = 0;
			mQuality = sharedPrefs.getString("sound_quality", "low");
			PreloadSongTask preloadSong = new PreloadSongTask(songIndex, mp, mQuality);
			preloadSong.execute("");
			// Displaying Song title
			String songTitle = SongsManager.getActualPlayList().getSongList().get(songIndex).getSongTitle();
        	songTitleLabel.setText(songTitle);
        	// Displaying Image song
        	String imageURI = SongsManager.getActualPlayList().getSongList().get(songIndex).getSongImage();
			WebImage webImage = new WebImage(songImageTarget, imageURI, WebImage.SCREEN, true);
			webImage.execute("");

        	// Changing Button Image to pause image
			btnPlay.setImageResource(R.drawable.btn_pause);
			
			// set Progress bar values
			songProgressBar.setProgress(0);
			songProgressBar.setMax(100); // 

			// Updating progress bar
			updateProgressBar();
		} catch (IllegalArgumentException e) {
			Toast.makeText(me, e.getMessage(), Toast.LENGTH_SHORT).show();
			dialog.dismiss();
			dialog = null;
		} catch (IllegalStateException e) {
			Toast.makeText(me, e.getMessage(), Toast.LENGTH_SHORT).show();
			dialog.dismiss();
			dialog = null;
		} 
	}
	
	/**
	 * Function to play a song
	 * @param songIndex - index of song
	 * */
	public void playSong(int songIndex, Context context){
		if(dialog != null){
			dialog.dismiss();
			dialog = null;
		}
		try{
			dialog = MusicSonarDialog.show(me, getText(R.string.loading_buffer_title), getText(R.string.loading_buffer_text), true, false, new DialogInterface.OnCancelListener() {
				
				public void onCancel(DialogInterface dialog) {
					Toast.makeText(me, getText(R.string.dialog_message_closed), Toast.LENGTH_SHORT).show();
				}
			});
		}catch(Exception e){
			dialog.cancel();
			Toast.makeText(me, e.getMessage(), Toast.LENGTH_SHORT).show();
		}
		playSong(songIndex, dialog);
	}

	private class PreloadSongTask extends AsyncTask<String, String, Void> {

		private int songIndex;
		private MusicSonarPlayer mp;
		private String mQuality;

		private Boolean isError = Boolean.FALSE;
		private String msg = "";

		public PreloadSongTask(int songIndex, MusicSonarPlayer mp, String mQuality){
			this.songIndex = songIndex;
			this.mp = mp;
			this.mQuality = mQuality;
		}

		protected void onPreExecute() {
			dialog.setCancelable(true);
		}

		protected Void doInBackground(String... params) {
			try {
				SongsManager.actualSong = SongsManager.getActualPlayList().getSongList().get(songIndex);
				
				mp.reset();
	        	mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
	        	mp.setDataSource(MusicSonarConstant.MP3_URL_LINK + mQuality + "/" + "?url=" + SongsManager.actualSong.getSongPath());
				mp.setTotalDuration(SongsManager.getActualPlayList().getSongList().get(songIndex).getSegundos().intValue());
				mp.prepare();
				mp.setOnErrorListener(new MediaPlayer.OnErrorListener() {
					
					public boolean onError(MediaPlayer mp, int what, int extra) {
						if(MusicSonarConstant.error_translate.get(""+what) != null){
							MusicSonarUtils.showToast(me, "Error : " + getText(MusicSonarConstant.error_translate.get(""+what)));
						}else{
							MusicSonarUtils.showToast(me, "Error : " + what);
						}
						if(mp != null){
							mp.stop();
							mp.reset();
							((MusicSonarPlayer)mp).setTotalDuration(0);
						}
						clearPlayerScreen();
						return true;
					}
				});
				mp.start();
				errorCount = 0;
			}catch(Exception e){
				isError = Boolean.TRUE;
				msg = getText(MusicSonarConstant.error_translate.get(String.valueOf(e.getMessage()))).toString() + " :: " + String.valueOf(e.getMessage());
				errorCount++;
			}
			return null;
		}

		protected void onProgressUpdate(String... progress) {
			// ProgressUpdate
		}

		protected void onPostExecute(Void result) {
			if(dialog != null){
				dialog.dismiss();
				dialog = null;
			}
			if(isError){
				MusicSonarUtils.showToast(me, msg);
				clearPlayerScreen();
				if(errorCount < 3){
					playSong(currentSongIndex, me);
				}
			}
		}
	}
	
	/**
	 * Update timer on seekbar
	 * */
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);        
    }	
	
	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = mp.getTotalDuration();
			   long currentDuration = 0;
			   try{
				   currentDuration = mp.getCurrentPosition();
			   }catch(Exception e){
				   currentDuration = MusicSonarUtils.TimerToMilliSeconds(songCurrentDurationLabel.getText());
			   }
			  
			   // Displaying Total Duration time
			   songTotalDurationLabel.setText(""+MusicSonarUtils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   songCurrentDurationLabel.setText(""+MusicSonarUtils.milliSecondsToTimer(currentDuration));
			   
			   // Updating progress bar
			   int progress = (int)(MusicSonarUtils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			   songProgressBar.setProgress(progress);
			   
			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};
		
	/**
	 * 
	 * */
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
		
	}

	/**
	 * When user starts moving the progress handler
	 * */
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
    }
	
	/**
	 * When user stops moving the progress hanlder
	 * */
    public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = mp.getTotalDuration();
		int currentPosition = MusicSonarUtils.progressToTimer(seekBar.getProgress(), totalDuration);
		
		// forward or backward to certain seconds
		mp.seekTo(currentPosition);
		
		// update timer progress again
		updateProgressBar();
    }

	/**
	 * On Song Playing completed
	 * if repeat is ON play same song again
	 * if shuffle is ON play random song
	 * */
	public void onCompletion(MediaPlayer mp) {
		// Validate items in songsList available
		if(SongsManager.getActualPlayList().getSongList().size() > 0){
			// check for repeat is ON or OFF
			/*if(isRepeat){
				// repeat is on play same song again
				//playSong(currentSongIndex, me);
				// forward or backward to certain seconds
				mp.seekTo(0);
				
				// update timer progress again
				updateProgressBar();
				mp.start();
			} else*/ if(isShuffle){
				// shuffle is on - play a random song
				Random rand = new Random();
				playSong(rand.nextInt((SongsManager.getActualPlayList().getSongList().size() - 1) - 0 + 1) + 0, me);
			} else{
				// no repeat or shuffle ON - play next song
				if(currentSongIndex < (SongsManager.getActualPlayList().getSongList().size() - 1)){
					playSong(currentSongIndex + 1, me);
				}else{
					// play first song
					playSong(0, me);
				}
			}
		} else {
			mp.stop();
			// Clearing Screen
			clearPlayerScreen();
		}
	}

	private void clearPlayerScreen(){
		songTotalDurationLabel.setText("");
		songCurrentDurationLabel.setText("");
		songTitleLabel.setText(R.string.app_name);
		songImageTarget.setImageResource(R.drawable.no_image);

		songProgressBar.setProgress(0);
		songProgressBar.setMax(0);
		songProgressBar.setSecondaryProgress(0);

		btnPlay.setImageResource(R.drawable.btn_play);
	}
	
	@Override
	 public void onDestroy(){
		mp.release();
		tracker.stopSession();
		super.onDestroy();
	 }

	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		songProgressBar.setSecondaryProgress(percent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (Integer.parseInt(android.os.Build.VERSION.SDK) < 5
                && keyCode == KeyEvent.KEYCODE_BACK
                && event.getRepeatCount() == 0) {
            Log.d("CDA", "onKeyDown Called");
            onBackPressed();
        }

        return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onBackPressed() {
        Log.d("CDA", "onBackPressed Called");
        Intent setIntent = new Intent(Intent.ACTION_MAIN);
        setIntent.addCategory(Intent.CATEGORY_HOME);
        setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(setIntent); 

        return;
	}

}